package com.example.demo.controller;

import com.example.demo.config.UserConfiguration;
import com.example.demo.model.PersonForm;
import com.example.demo.test.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liukui on 2017/7/1.
 */
@Controller
public class HomeController extends WebMvcConfigurerAdapter {

    @Resource
    private UserConfiguration userConfiguration;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @RequestMapping("/")
    public String index(Model model,Person person2) {
        Person single = new Person("aa", 11);
        List<Person> people = new ArrayList<>();

        Person p1 = new Person("zhangsan", 11);
        Person p2 = new Person("lisi", 22);
        Person p3 = new Person("wangwu", 33);
        people.add(p1);
        people.add(p2);
        people.add(p3);
        model.addAttribute("singlePerson", single);
        model.addAttribute("people", people);
        return "index";
    }

    @RequestMapping("/login")
    public String actionLoginShow(Model model) {

        System.out.println(userConfiguration.getSystemName() + " " + userConfiguration.getSystemName2());
        model.addAttribute("config", userConfiguration);
        return "login";
    }

    @GetMapping("/form")
    public String showForm(PersonForm personForm) {
        return "form";
    }

    @PostMapping("/form")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "form";
        }

        return "redirect:/results";
    }
}
